package com.opticon.vaadinR.ui.panel;

import com.google.common.io.Files;
import com.vaadin.Application;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * This class is a
 */
public class SimpleTableTab extends VerticalLayout {
    private static Logger logger = Logger.getLogger(SimpleTableTab.class);

    private String COLUMN_LABEL_TYPE = "key";
    private String COLUMN_LABEL_ATTRIBUTE = "attr";
    private String COLUMN_LABEL_VALUE = "value";

    private String iTitle = "SimpleTableTab";
    public Table iTable = null;
    private final File iFile;
    private final Application iApplication;

    public SimpleTableTab(File aFile, Application aApplication) {
        iFile = aFile;
        iApplication = aApplication;
        initialize();
    }



    private void loadData() {
        String lFirstLine = null;
        try {
            List<String> lContent = Files.readLines(iFile, Charset.defaultCharset());
            lFirstLine = lContent.get(0).replaceAll("\"","");

            String[] lHeader = lFirstLine.split(",");

            createTableColumns(lHeader);

            for (int i = 1; i < lContent.size(); i++) {
                String line = lContent.get(i);
                String[] lColumns = line.split(",");


                // Add a new item to the table.
                Object id = iTable.addItem();
                for (int j = 0; j < lColumns.length; j++) {
                    iTable.getContainerProperty(id, lHeader[j]).setValue(lColumns[j]);
                }

            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }


    }

    public Component getComponent() {
        return this;
    }

    public void initialize() {
        this.removeAllComponents();

        iTable = new Table();
        iTable.setSizeFull();

        loadData();

        addComponent(iTable);

        setCaption();

        this.requestRepaintAll();
    }


    /**
     * Create the
     *
     * @param aHeader
     */
    private void createTableColumns(String[] aHeader) {
        // Define the Table
        for (String lColumnName : aHeader) {
            iTable.addContainerProperty(lColumnName, Label.class, null);
        }
    }

    /**
     * Table formatting
     */
    private void doFormatting() {
        iTable.setWidth("100%");
        iTable.setPageLength(4);
    }


    /**
     * Sets the field's caption <code>String</code>. Caption is the visible
     * name of the field. This method will trigger a
     * {@link com.vaadin.terminal.Paintable.RepaintRequestEvent
     * RepaintRequestEvent}.
     */
    public void setCaption() {
        super.setCaption(iTitle);
    }
}
